﻿using Entity;
using Entity.Sale;
using ServiceCore;
using ServiceCore.Tool.Text;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Dapper;
using ServiceCore.Tool.Barcode;

namespace Customer.Bussiness_Service
{
    public interface Isale_service
    {
        /// <summary>
        ///   销售主管获取用户列表
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        ResultListModel get_sale_userpagelist(get_sale_userpagelist_params query);
        /// <summary>
        ///  销售设置用户基础信息
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        ResultModel sale_set_user_base(sale_set_user_base_params model);
        /// <summary>
        /// 分配销售经理
        /// </summary>
        /// <param name="userid"></param>
        /// <param name="uid"></param>
        /// <returns></returns>
        ResultModel sale_distribution(string userid, string uid);
        /// <summary>
        ///  销售获取自己的客户列表
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        ResultListModel get_sale_myuserpagelist(get_sale_myuserpagelist_params query);
        /// <summary>
        ///  保存机器
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        ResultModel save_mch(create_mch_params model);
        /// <summary>
        ///  获取工单详情
        /// </summary>
        /// <param name="work_order_id"></param>
        /// <returns></returns>
        ResultObjModel get_work_model(string work_order_id);
        /// <summary>
        /// 分页查询
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        ResultListModel<get_work_order_details_pagelist_showlis> get_work_order_details_pagelist(get_work_order_details_pagelist_params query);
        /// <summary>
        /// 生产下单
        /// </summary>
        /// <param name="work_order_id"></param>
        /// <returns></returns>
        //ResultObjModel start_work(string work_order_id);
        ResultObjModel start_work(string[] work_order_ids);
        /// <summary>
        /// 删除生产单
        /// </summary>
        /// <param name="work_order_id"></param>
        /// <returns></returns>
        ResultObjModel del_work(string work_order_id);
        /// <summary>
        /// 获取生产单柜体详情
        /// </summary>
        /// <param name="work_order_details_id"></param>
        /// <returns></returns>
        ResultObjModel get_work_details_model(string work_order_details_id);
        /// <summary>
        /// 获取销售列表
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        ResultObjModel get_Sale_list(string name);
        /// <summary>
        /// 销售主管页获取生产单列表
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        ResultListModel<get_work_order_details_pagelist_showlis> get_manager_workorder_list(get_work_order_details_pagelist_params query);
        /// <summary>
        /// 根据大订单号获取对应生产单信息
        /// </summary>
        /// <param name="work_order_id"></param>
        /// <returns></returns>
        ResultObjModel get_work_details_list(string work_order_id);

 

        /// <summary>
        /// 审核通过 转生产
        /// </summary>
        /// <param name="work_order_id"></param>
        /// <param name="uid"></param>
        /// <returns></returns>
        ResultModel to_work(string work_order_id, string uid);
        /// <summary>
        /// 更改客户
        /// </summary>
        /// <param name="work_order_id"></param>
        /// <param name="new_baseuserid"></param>
        /// <returns></returns>
        ResultModel change_baseuserid(string work_order_id, string new_baseuserid);
        /// <summary>
        /// 获取用户信息
        /// </summary>
        /// <param name="old_baseuserid"></param>
        /// <param name="new_baseuserid"></param>
        /// <returns></returns>
        ResultObjModel get_user_mod(string old_baseuserid, string new_baseuserid);
        /// <summary>
        /// 设置工期
        /// </summary>
        /// <param name="work_order_id"></param>
        /// <param name="work_end_time"></param>
        /// <returns></returns>
        ResultModel set_work_end_time(string work_order_id, string work_end_time);
        /// <summary>
        /// 退回销售
        /// </summary>
        /// <param name="work_order_id"></param>
        /// <returns></returns>
        ResultModel approval_back_work(string work_order_id);
        /// <summary>
        /// 获取生产主管列表
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        ResultObjModel get_Work_Manager_list(string name);
    }
    public class sale_service : Isale_service
    {
        private readonly IToole_DI _tool;

        private readonly IMchType_Helper _mchtype;
        private readonly IBarcode_Service _barcode_service;
        public sale_service(IToole_DI Tool, IMchType_Helper Mchtype, IBarcode_Service Barcode_service)
        {
            _tool = Tool;
            _mchtype = Mchtype;
            _barcode_service = Barcode_service;
        }
        private int get_return_pool_time_set
        {
            get
            {
                try
                {
                    return Convert.ToInt32(_tool.di_appSettingConfig["user_config:return_pool_time"]);
                }
                catch
                {
                    return 365;
                }
            }
        }
        #region 主管页
        /// <summary>
        /// 获取销售查询的用户列表
        /// </summary>
        /// <returns></returns>
        public ResultListModel get_sale_userpagelist(get_sale_userpagelist_params query)
        {
            return CoreStartDo.ResultAction<ResultListModel>(result =>
            {
                string sql = "select * from [user]";
                string where = " where  1=1";
                dynamic query_dy = new System.Dynamic.ExpandoObject();
                if (query.search_type.HasValue)
                {
                    switch (query.search_type.Value)
                    {
                        case search_enum_type.客户姓名:
                            where += " and Name like @user_name";
                            query_dy.user_name = $"%{query.search_value}%";
                            break;
                        case search_enum_type.客户微信号:
                            where += " and wx_name like @user_wx_name";
                            query_dy.user_wx_name = $"%{query.search_value}%";
                            break;
                        case search_enum_type.客户电话:
                            where += " and Tel like @user_tel";
                            query_dy.user_tel = $"%{query.search_value}%";
                            break;
                    }
                }
                if (!string.IsNullOrWhiteSpace(query.sale_uid))
                {
                    where += " and sale_uid=@sale_uid";
                    query_dy.sale_uid = query.sale_uid;
                }
                if (query.source.HasValue)
                {
                    where += " and source=@source";
                    query_dy.source = query.source;
                }

                
                //创建日期查询
                if (!string.IsNullOrWhiteSpace(query.createon_sdt))
                {
                    where += " and CreateOn>=@createon_sdt";
                    query_dy.createon_sdt = query.createon_sdt;
                } 
                if (!string.IsNullOrWhiteSpace(query.createon_edt))
                {
                    where += " and CreateOn<=@createon_edt";
                    query_dy.createon_edt = query.createon_edt;
                }




                //认领日期查询
                if (!string.IsNullOrWhiteSpace(query.collection_time_sdt))
                {
                    where += " and collection_time>=@collection_time_sdt";
                    query_dy.collection_time_sdt = query.collection_time_sdt;
                }
                if (!string.IsNullOrWhiteSpace(query.collection_time_edt))
                {
                    where += " and collection_time<=@collection_time_edt";
                    query_dy.collection_time_edt = query.collection_time_edt;
                } 


  
                //认领日期查询
                if (!string.IsNullOrWhiteSpace(query.return_pool_time_sdt))
                {
                    where += " and return_pool_time>=@return_pool_time_sdt";
                    query_dy.return_pool_time_sdt = query.return_pool_time_sdt;
                } 
                if (!string.IsNullOrWhiteSpace(query.return_pool_time_edt))
                {
                    where += " and return_pool_time<=@return_pool_time_edt";
                    query_dy.return_pool_time_edt = query.return_pool_time_edt;
                }
                 
                ResultListModel<User> result_pagelist = _tool.di_db.GetRKPageList<User>(sql, where, "CreateOn", query_dy, query.IsPage, query.page, query.pagesize);
                var q = from o in result_pagelist.rows
                        select new
                        {
                            o.Id,
                            o.CreateOn,
                            o.sale_uid,
                            o.sale_name,
                            o.return_pool_time,
                            o.collection_time,
                            o.Name,
                            o.UserName,
                            o.wx_name,
                            source = o.source.ToString(),
                            o.Tel
                        };
                result.code = 0;
                result.msg = "success";
                result.rows = q.ToList();
                result.total = result_pagelist.total;
                result.current = query.page.Value;
                return result;
            });
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public ResultModel sale_set_user_base(sale_set_user_base_params model)
        {
            return CoreStartDo.ResultAction<ResultModel>(result =>
            {
                if (string.IsNullOrWhiteSpace(model.Id))
                {
                    result.code = 1;
                    result.msg = "参数不完整";
                    return result;
                }
                if (string.IsNullOrWhiteSpace(model.Tel))
                {
                    result.code = 1;
                    result.msg = "电话号码必须填写";
                    return result;
                }
                if (string.IsNullOrWhiteSpace(model.wx_name))
                {
                    result.code = 1;
                    result.msg = "客户微信名必须填写";
                    return result;
                }
                if (string.IsNullOrWhiteSpace(model.Name))
                {
                    result.code = 1;
                    result.msg = "客户名称不能为空";
                    return result;
                }
                if (!model.source.HasValue)
                {
                    result.code = 1;
                    result.msg = "必须选择客户渠道";
                    return result;
                }
                int update_row = _tool.di_db.do_rk_Execute("update [user] set Tel=@Tel,wx_name=@wx_name,Name=@Name,source=@source where Id=@Id", model);
                if (update_row > 0)
                {
                    result.code = 0;
                    result.msg = "保存成功";
                }
                else
                {
                    result.code = 1;
                    result.msg = "保存失败";
                }
                return result;
            });
        }
        /// <summary>
        /// 分配销售
        /// </summary>
        public ResultModel sale_distribution(string userid, string uid)
        {
            return CoreStartDo.ResultAction<ResultModel>(result =>
            {
                if (string.IsNullOrWhiteSpace(userid))
                {
                    result.code = 1;
                    result.msg = "必须选择客户";
                    return result;
                }
                if (string.IsNullOrWhiteSpace(uid))
                {
                    result.code = 1;
                    result.msg = "请选择销售";
                    return result;
                }
                User umod = _tool.di_db.Get_rk_List<User>("select top 1 * from [user] where  Id=@id", new { id = userid }).FirstOrDefault();
                if (umod == null)
                {
                    result.code = 1;
                    result.msg = "客户不存在";
                }
                rk_user usermode = _tool.di_db.GetList<rk_user>("select top 1 * from rk_user  where  uid=@id", new { id = uid }).FirstOrDefault();
                if (usermode == null)
                {
                    result.code = 1;
                    result.msg = "设置销售不存在";
                }
                //开始修改对应用户数据
                int updaterow = _tool.di_db.do_rk_Execute("update [user] set sale_uid=@sale_uid,sale_name=@sale_name,collection_time=@collection_time,return_pool_time=@return_pool_time where Id=@id", new { sale_uid = usermode.uid, sale_name = usermode.u_name, collection_time = DateTime.Now, return_pool_time = DateTime.Now.AddDays(get_return_pool_time_set), id = userid });
                if (updaterow > 0)
                {
                    result.code = 0;
                    result.msg = "保存成功";
                }
                else
                {
                    result.code = 1;
                    result.msg = "保存失败";
                }
                return result;
            });
        }
        #endregion
        #region 一般销售页
        /// <summary>
        /// 
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public ResultListModel get_sale_myuserpagelist(get_sale_myuserpagelist_params query)
        {
            return CoreStartDo.ResultAction<ResultListModel>(result =>
            {
                string sql = "select * from [user]";
                string where = " where  sale_uid=@sale_uid";
                dynamic query_dy = new System.Dynamic.ExpandoObject();
                query_dy.sale_uid = _tool.di_user.USER.uid;
                if (query.search_type.HasValue)
                {
                    switch (query.search_type.Value)
                    {
                        case search_enum_type.客户姓名:
                            where += " and Name like @user_name";
                            query_dy.user_name = $"%{query.search_value}%";
                            break;
                        case search_enum_type.客户微信号:
                            where += " and wx_name like @user_wx_name";
                            query_dy.user_wx_name = $"%{query.search_value}%";
                            break;
                        case search_enum_type.客户电话:
                            where += " and Tel like @user_tel";
                            query_dy.user_tel = $"%{query.search_value}%";
                            break;
                    }
                }
                ResultListModel<User> result_pagelist = _tool.di_db.GetRKPageList<User>(sql, where, "collection_time", query_dy, query.IsPage, query.page, query.pagesize);
                var q = from o in result_pagelist.rows
                        select new
                        {
                            baseuserid = o.Id,
                            o.CreateOn,
                            o.collection_time,
                            o.return_pool_time,
                            baseusername = o.Name,
                            o.UserName,
                            o.Tel,
                            o.wx_name,
                            o.source,
                            source_str = o.source.ToString()
                        };
                result.code = 0;
                result.msg = "success";
                result.rows = q.ToList();
                result.total = result_pagelist.total;
                result.current = query.page.Value;
                return result;
            });
        }
        /// <summary>
        /// 创建机器
        /// </summary>
        /// <returns></returns>
        public ResultModel save_mch(create_mch_params model)
        {
            return CoreStartDo.ResultAction<ResultModel>(result =>
            {
                #region 开始进行基础验证
                if (string.IsNullOrWhiteSpace(model.work_order_id))
                {
                    model.work_order_id = "";
                }
                if (string.IsNullOrWhiteSpace(model.mchname))
                {
                    result.code = 1;
                    result.msg = "必须设置机器名称";
                    return result;
                }
                if (string.IsNullOrWhiteSpace(model.province) || string.IsNullOrWhiteSpace(model.city) || string.IsNullOrWhiteSpace(model.district) || string.IsNullOrWhiteSpace(model.address))
                {
                    result.code = 1;
                    result.msg = "必须设置完整的地区信息";
                    return result;
                }
                if (string.IsNullOrWhiteSpace(model.baseuserid))
                {
                    result.code = 1;
                    result.msg = "必须选择用户";
                    return result;
                }
                if (model.details == null || model.details.Count == 0)
                {
                    result.code = 1;
                    result.msg = "至少设置一台柜体";
                    return result;
                }
                if (!model.details.Where(s => s.box_no == 0).Any())
                {
                    result.code = 1;
                    result.msg = "必须设置一个主柜";
                    return result;
                }
                int[] sublist = model.details.Select(s => s.box_no).ToArray();
                int[] dissublist = model.details.Select(s => s.box_no).Distinct().ToArray();
                if (sublist.Length != dissublist.Length)
                {
                    result.code = 1;
                    result.msg = "提交柜体数据异常";
                    return result;
                }
                //验证提交用户是否存在
                var user = _tool.di_db.Get_rk_List<User>("select top 1 * from [User] where Id=@Id", new { Id = model.baseuserid }).FirstOrDefault();
                if (user == null)
                {
                    result.code = 1;
                    result.msg = "用户不存在";
                    return result;
                }
                #endregion
                var masterbox = model.details.Where(s => s.box_no == 0).FirstOrDefault();
                #region 数据整合 
                string mchid = "Temp_" + _tool.di_getid.IGet_SnowFlake_Id;
                string MchMode = "";
                masterbox.Mch_Type = (Mch_Type)Convert.ToInt32(masterbox.mch_kid_type_id.Split("_")[0].ToString());
                switch (masterbox.Mch_Type)
                {
                    case Mch_Type.IC:
                        MchMode = "单片机";
                        break;
                    case Mch_Type.IC2:
                        MchMode = "安卓机";
                        break;
                    case Mch_Type.Adult:
                        MchMode = "格子柜";
                        break;
                    case Mch_Type.Keystroke:
                        MchMode = "按键机";
                        break;
                }
                string DT = DateTime.Now.ToString("yyyyMMddHHmmss");
                //创建工单
                sale_work_order new_work_order = new sale_work_order();
                new_work_order.work_order_id = string.IsNullOrWhiteSpace(model.work_order_id) ? DT.Substring(2, DT.Length - 2) : model.work_order_id;//如果是修改则赋予提交值 如果是新增则赋予新单号
                new_work_order.baseuserid = user.Id;
                new_work_order.baseusername = user.Name;
                new_work_order.addtime = DateTime.Now;
                new_work_order.add_uid = _tool.di_user.USER.uid;
                new_work_order.mch_name = model.mchname;
                new_work_order.mch_id = mchid;
                new_work_order.total_state = sale_work_state_enum.已新建未处理;
                new_work_order.province = model.province;
                new_work_order.city = model.city;
                new_work_order.district = model.district;
                new_work_order.address = model.address;
                new_work_order.work_order_mark = model.work_remark;
                //创建机器
                Mch newmch = new Mch();
                newmch.Id = mchid;
                newmch.Name = model.mchname;
                newmch.State = MchState.可用;
                newmch.Active = true;
                newmch.CreateOn = newmch.UpdateOn = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                newmch.CreateBy = newmch.UpdateBy = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                newmch.IsDelete = false;
                newmch.IsOnLine = false;
                newmch.MchMode = MchMode;
                newmch.BaseUserId = "RK_test";
                newmch.work_baseuserid = model.baseuserid;
                newmch.work_order_id = new_work_order.work_order_id;
                newmch.IC2_max_lattices = 100;
                newmch.province = model.province;
                newmch.city = model.city;
                newmch.district = model.district;
                newmch.Address = model.address;
                newmch.work_order_time = new_work_order.addtime;
                newmch.sale_uid = _tool.di_user.USER.uid;
                newmch.sale_name = _tool.di_user.USER.u_name;
                //创建工单详情 
                List<sale_work_order_details> new_work_order_details = new List<sale_work_order_details>();
                //创建柜体
                List<Mch_subsidiary> new_boxs = new List<Mch_subsidiary>();
                foreach (var item in model.details)
                {
                    slot_template slot_template_mode = _tool.di_db.GetList<slot_template>("select * from slot_template where template_id=@template_id", new { item.template_id }).FirstOrDefault();
                    int box_capacity = 100;
                    //获取当前货道设置
                    List<SlotGroup> slot_list = Newtonsoft.Json.JsonConvert.DeserializeObject<List<SlotGroup>>(slot_template_mode.slot_group);
                    //定义模板容器
                    List<slotItem> slot_set = new List<slotItem>();
                    //标记公式  实际货道号 应该等于  ((当前行数-1）* 单行最大设置值10) + 当前列数  + 请求柜体 * 单柜数量
                    foreach (var itemRow in slot_list)
                    {
                        int rowsIndex = itemRow.row_index.Value;
                        var column_Array = itemRow.column_list.Where(s => s.count.HasValue).ToList();
                        foreach (var itemColumn in column_Array)
                        {
                            slot_set.Add(new slotItem()
                            {
                                index = (10 * (rowsIndex - 1)) + itemColumn.column_index.Value + item.box_no * box_capacity,
                                maxcount = itemColumn.count.Value,
                                height = itemRow.hight
                            });
                        }
                    }
                    var kid_type_model = item.mch_kid_type_id.Split("_");
                    item.Mch_Type = (Mch_Type)Convert.ToInt32(kid_type_model[0]);
                    item.mch_kid_type = kid_type_model[2].ToString();
                    string print_Str = item.box_no == 0 ? "主柜" : (_tool.NumToChinese((item.box_no + 1).ToString()) + "副"); //生成打印生产单时的显示数据 
                    //开始定义单柜生产数据 
                    sale_work_order_details new_item = new sale_work_order_details();
                    new_item.work_order_details_id = new_work_order.work_order_id + item.box_no.ToString("0");
                    new_item.work_order_id = new_work_order.work_order_id;
                    new_item.print_work_No = $"{model.details.Count.ToString()}-{item.box_no + 1} {item.mch_kid_type} {print_Str}";
                    new_item.des = print_Str;
                    new_item.slot_set = Newtonsoft.Json.JsonConvert.SerializeObject(slot_set); //item.slot_set;
                    new_item.addtime = DateTime.Now;
                    new_item.add_uid = _tool.di_user.USER.uid;
                    new_item.slot_template_id = item.template_id;
                    new_item.work_mark = "";
                    new_item.box_No = item.box_no;
                    new_item.box_id = "NoData";
                    new_item.color = item.color;
                    new_item.can_cold = item.can_cold;
                    new_item.can_hot = item.can_hot;
                    new_item.can_anion = item.can_anion;
                    new_item.can_cash = item.can_cash;
                    new_item.Mch_Type = item.Mch_Type.Value;
                    new_item.mch_kid_type = item.mch_kid_type;
                    new_item.mch_kid_type_id = item.mch_kid_type_id;
                    new_work_order_details.Add(new_item);
                    //开始定义单柜系统数据
                    Mch_subsidiary new_mod = new Mch_subsidiary();
                    new_mod.Id = _tool.di_getid.IGet_SnowFlake_Id;
                    new_mod.mchid = newmch.Id;
                    new_mod.box_no = item.box_no;
                    new_mod.addtime = DateTime.Now;
                    new_mod.color = item.color;
                    new_mod.can_cold = item.can_cold;
                    new_mod.can_hot = item.can_hot;
                    new_mod.can_anion = item.can_anion;
                    new_mod.can_cash = item.can_cash;
                    new_mod.Mch_Type = item.Mch_Type.Value;
                    new_mod.mch_kid_type = item.mch_kid_type;
                    new_mod.mch_kid_type_id = item.mch_kid_type_id;
                    new_mod.slot_template_id = item.template_id;
                    new_mod.baseuserid = newmch.BaseUserId;
                    new_mod.work_baseuserid = newmch.work_baseuserid;
                    new_mod.print_work_No = new_item.print_work_No;
                    new_mod.work_order_id = new_work_order.work_order_id;
                    new_boxs.Add(new_mod);
                }
                #endregion
                if (string.IsNullOrWhiteSpace(model.work_order_id))
                {
                    #region 开启两个数据库的事务
                    string error = "";
                    int Masterdb_rows = _tool.di_db.StartTran((conn, tran) =>
                    {
                        int rows = 0;
                        //工单
                        rows += conn.Execute(_tool.di_db.AddBySqlStr<sale_work_order>(), new_work_order, tran);
                        //工单详情
                        rows += conn.Execute(_tool.di_db.AddBySqlStr<sale_work_order_details>(), new_work_order_details, tran);
                        return rows;
                    }, ref error);
                    if (Masterdb_rows > 0)
                    {
                        ///第一步事务成功，开始进行下一步
                        string rkerror = "";
                        int rkdb_rows = _tool.di_db.StartRKTran((conn, tran) =>
                        {
                            int rows = 0;
                            //机器
                            rows += conn.Execute(_tool.di_db.AddBySqlStr<Mch>(), newmch, tran);
                            //机器柜体情况
                            rows += conn.Execute(_tool.di_db.AddBySqlStr<Mch_subsidiary>(), new_boxs, tran);
                            return rows;
                        }, ref rkerror);
                        if (rkdb_rows > 0)
                        {
                            result.code = 0;
                            result.msg = "添加成功";
                        }
                        else
                        {
                            result.code = 1;
                            result.msg = "添加失败 rkdb fail=>" + rkerror;
                        }
                    }
                    else
                    {
                        result.code = 1;
                        result.msg = "添加失败 db fail=>" + error;
                    }
                    #endregion 
                    return result;
                }
                else
                {
                    #region 处理修改业务
                    //验证数据是否存在
                    var check_order_work_model = _tool.di_db.GetList<sale_work_order>("select * from sale_work_order  where work_order_id=@work_order_id", new { model.work_order_id }).FirstOrDefault();
                    if (check_order_work_model == null)
                    {
                        result.code = 1;
                        result.msg = "修改工单数据不存在";
                        return result;
                    }
                    if (check_order_work_model.total_state != sale_work_state_enum.已新建未处理
                    && check_order_work_model.total_state != sale_work_state_enum.审批被驳回 
                    )
                    {
                        result.code = 1;
                        result.msg = $"当前审核状态{check_order_work_model.total_state.ToString()},不允许修改";
                        return result;
                    }
                    newmch.Id = check_order_work_model.mch_id;
                    //开始修改  
                    string error = "";
                    int Masterdb_rows = _tool.di_db.StartTran((conn, tran) =>
                    {
                        int rows = 0;
                        //工单
                        rows += conn.Execute(_tool.di_db.UpdateBySqlstr<sale_work_order>(new string[] { "mch_name", "total_state", "province", "city", "district", "address", "work_order_mark" }, new string[] { "work_order_id=@work_order_id" }), new_work_order, tran);
                        rows += conn.Execute("delete from sale_work_order_details where work_order_id=@work_order_id", new { model.work_order_id }, tran);
                        //工单详情
                        rows += conn.Execute(_tool.di_db.AddBySqlStr<sale_work_order_details>(), new_work_order_details, tran);
                        return rows;
                    }, ref error);
                    if (Masterdb_rows > 0)
                    {
                        ///第一步事务成功，开始进行下一步
                        string rkerror = "";
                        int rkdb_rows = _tool.di_db.StartRKTran((conn, tran) =>
                        {
                            int rows = 0;
                            //机器
                            rows += conn.Execute(_tool.di_db.UpdateBySqlstr<Mch>(new string[] { "Name", "MchMode", "province", "city", "district", "address", }, new string[] { "Id=@Id" }), newmch, tran);
                            //机器柜体情况
                            rows += conn.Execute("delete from Mch_subsidiary where work_order_id=@work_order_id", new { model.work_order_id }, tran);
                            rows += conn.Execute(_tool.di_db.AddBySqlStr<Mch_subsidiary>(), new_boxs, tran);
                            return rows;
                        }, ref rkerror);
                        if (rkdb_rows > 0)
                        {
                            result.code = 0;
                            result.msg = "修改成功";
                        }
                        else
                        {
                            result.code = 1;
                            result.msg = "修改失败 rkdb fail=>" + rkerror;
                        }
                    }
                    else
                    {
                        result.code = 1;
                        result.msg = "修改失败 db fail=>" + error;
                    }
                    #endregion
                }
                return result;
            });
        }
        /// <summary>
        /// 获取工单详情
        /// </summary>
        /// <param name="work_order_id"></param>
        /// <returns></returns>
        public ResultObjModel get_work_model(string work_order_id)
        {
            return CoreStartDo.ResultAction(result =>
            {
                if (string.IsNullOrWhiteSpace(work_order_id))
                {
                    result.code = 1;
                    result.msg = "参数不完整";
                }
                //开始获取数据
                var model = _tool.di_db.GetList<sale_work_order>("select top 1 * from sale_work_order where work_order_id=@work_order_id", new { work_order_id }).FirstOrDefault();
                var list = _tool.di_db.GetList<sale_work_order_details>("select * from sale_work_order_details where work_order_id=@work_order_id", new { work_order_id }).ToList();
                var needdetails = from o in list
                                  select new createmch
                                  {
                                      box_no = o.box_No,
                                      can_anion = o.can_anion,
                                      can_cash = o.can_cash,
                                      can_cold = o.can_cold,
                                      can_hot = o.can_hot,
                                      color = o.color,
                                      mch_kid_type = o.mch_kid_type,
                                      Mch_Type = o.Mch_Type,
                                      slot_set = o.slot_set,
                                      mch_kid_type_id = o.mch_kid_type_id,
                                      template_id = o.slot_template_id
                                  };
                create_mch_params resultmodel = new create_mch_params()
                {
                    work_order_id = model.work_order_id,
                    mchname = model.mch_name,
                    province = model.province,
                    city = model.city,
                    district = model.district,
                    address = model.address,
                    work_remark = model.work_order_mark,
                    baseuserid = model.baseuserid,
                    details = needdetails.ToList(),
                };
                result.code = 0;
                result.msg = "success";
                result.data = resultmodel;
                return result;
            });
        }
 
        /// <summary>
        /// 获取工单详情
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public ResultListModel<get_work_order_details_pagelist_showlis> get_work_order_details_pagelist(get_work_order_details_pagelist_params query)
        {
            return CoreStartDo.ResultAction<ResultListModel<get_work_order_details_pagelist_showlis>>(result =>
            {

                string core_sql = $"select {string.Join(',', _tool.search_workorder_Item)} from sale_work_order_details a left JOIN sale_work_order b on a.work_order_id = b.work_order_id left join slot_template c on a.slot_template_id = c.template_id";
                string where = " where b.add_uid=@sale_uid";
                dynamic query_dy = new System.Dynamic.ExpandoObject();
                query_dy.sale_uid = _tool.di_user.USER.uid;
                if (!string.IsNullOrWhiteSpace(query.baseusername))
                {
                    where += " and  b.baseusername like @baseusername";
                    query_dy.baseusername = $"%{query.baseusername}%";
                }
                if (!string.IsNullOrWhiteSpace(query.mchname))
                {
                    where += " and  b.mch_name like @mchname";
                    query_dy.mchname = $"%{ query.mchname}%";
                }
                if (!string.IsNullOrWhiteSpace(query.work_order_details_id))
                {
                    where += " and  a.work_order_details_id like @work_order_details_id";
                    query_dy.work_order_details_id = $"%{query.work_order_details_id}%";
                }
                if (query.work_approval_state.HasValue)
                {
                    where += " and  b.work_approval_state=@work_approval_state";
                    query_dy.work_approval_state = query.work_approval_state;
                }
                if (query.work_state.HasValue)
                {
                    where += " and  b.work_state=@work_state";
                    query_dy.work_state = query.work_state;
                }
                if (query.logistics_state.HasValue)
                {
                    where += " and  b.logistics_state=@logistics_state";
                    query_dy.logistics_state = query.logistics_state;
                }
                ResultListModel<get_work_order_details_pagelist_showlis> result_pagelist = _tool.di_db.GetPageList<get_work_order_details_pagelist_showlis>(core_sql, where, "b.addtime", query_dy, query.IsPage, query.page, query.pagesize);
                return result_pagelist;
            });
        }
        /// <summary>
        /// 生成生产单
        /// </summary>
        /// <returns></returns>
        public ResultObjModel start_work(string[] work_order_ids)
        {
            return CoreStartDo.ResultAction(result =>
            {
                if (work_order_ids == null)
                {
                    result.code = 1;
                    result.msg = "未找到参数";
                    return result;
                }
                if (!work_order_ids.Any())
                {
                    result.code = 1;
                    result.msg = "至少选择一项";
                    return result;
                }
                work_order_ids = work_order_ids.Distinct().ToArray();
                List<sale_work_order> update_row = _tool.di_db.GetList<sale_work_order>("select top 1 * from sale_work_order where work_order_id in @work_order_ids", new { work_order_ids }).ToList();
                if (!update_row.Any())
                {
                    result.code = 1;
                    result.msg = "未找到任何更新项";
                    return result;
                }
                foreach (var item in update_row)
                {
                    if (item.total_state != sale_work_state_enum.已新建未处理 && item.total_state != sale_work_state_enum.审批被驳回 && item.total_state != sale_work_state_enum.生产退回)
                    {
                        result.code = 1;
                        result.msg = $"当前生产单状态{item.total_state.ToString()},无法生成生产单";
                        return result;
                    }
                }

                int ur = _tool.di_db.do_Execute("update sale_work_order set total_state=@total_state,work_approval_state=@work_approval_state,create_order_time=@create_order_time where work_order_id in @work_order_ids", new
                {
                    total_state = sale_work_state_enum.审批处理中,
                    work_approval_state = work_order_approval.待审核,
                    work_order_ids,
                    create_order_time = DateTime.Now //设置生成生产单时间
                });
                //更新机器下单时间
                _tool.di_db.do_rk_Execute("update Mch set work_order_time=@work_order_time where Id in @mchid", new { work_order_time = DateTime.Now, mchid = update_row.Select(s => s.mch_id).ToArray() });
                if (ur > 0)
                {
                    result.code = 0;
                    result.msg = "提交成功";
                }
                else
                {
                    result.code = 1;
                    result.msg = "提交失败";
                }
                return result;
            });
        }
        /// <summary>
        /// 删除生产单
        /// </summary>
        /// <returns></returns>
        public ResultObjModel del_work(string work_order_id)
        {
            return CoreStartDo.ResultAction(result =>
            {
                if (string.IsNullOrWhiteSpace(work_order_id))
                {
                    result.code = 1;
                    result.msg = "未找到参数";
                    return result;
                }
                sale_work_order update_row = _tool.di_db.GetList<sale_work_order>("select top 1 * from sale_work_order where work_order_id=@work_order_id", new { work_order_id }).FirstOrDefault();
                if (update_row == null)
                {
                    result.code = 1;
                    result.msg = "未找到更新项";
                    return result;
                }
                if (update_row.total_state != sale_work_state_enum.已新建未处理 && update_row.total_state != sale_work_state_enum.审批被驳回 && update_row.total_state != sale_work_state_enum.生产退回)
                {
                    result.code = 1;
                    result.msg = $"当前生产单状态{update_row.total_state.ToString()},无法删除 ";
                    return result;
                }
                #region 开启两个数据库的事务
                string error = "";
                int Masterdb_rows = _tool.di_db.StartTran((conn, tran) =>
                {
                    int rows = 0;
                    //工单
                    rows += conn.Execute("delete from sale_work_order where work_order_id=@work_order_id", new { work_order_id }, tran);
                    //工单详情
                    rows += conn.Execute("delete from sale_work_order_details where work_order_id=@work_order_id", new { work_order_id }, tran);
                    return rows;
                }, ref error);
                if (Masterdb_rows > 0)
                {
                    ///第一步事务成功，开始进行下一步
                    string rkerror = "";
                    int rkdb_rows = _tool.di_db.StartRKTran((conn, tran) =>
                    {
                        int rows = 0;
                        //机器
                        rows += conn.Execute("delete from Mch where id=@id", new { id = update_row.mch_id }, tran);
                        //机器柜体情况
                        rows += conn.Execute("delete from Mch_subsidiary where work_order_id=@work_order_id", new { work_order_id }, tran);
                        return rows;
                    }, ref rkerror);
                    if (rkdb_rows > 0)
                    {
                        result.code = 0;
                        result.msg = "删除成功";
                    }
                    else
                    {
                        result.code = 1;
                        result.msg = "删除失败 rkdb fail=>" + rkerror;
                    }
                }
                else
                {
                    result.code = 1;
                    result.msg = "删除失败 db fail=>" + error;
                }
                #endregion
                return result;
            });
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="work_order_details_id"></param>
        /// <returns></returns>
        public ResultObjModel get_work_details_model(string work_order_details_id) {
            return CoreStartDo.ResultAction(result =>
            {
                //获取
                var box_mod = _tool.di_db.GetList<get_details_model>("select top 1 a.*,b.*,c.u_name,d.slot_group from sale_work_order_details a left join sale_work_order b on a.work_order_id = b.work_order_id left join rk_user c on b.add_uid = c.uid left join slot_template d on a.slot_template_id = d.template_id where work_order_details_id=@work_order_details_id", new { work_order_details_id }).FirstOrDefault();
                if (box_mod != null)
                {
                    box_mod.barcode = _barcode_service.GenerateBarCodeBitmap(box_mod.work_order_details_id);
                }
                result.code = 0;
                result.msg = "success";
                result.data = box_mod;
                return result;
            });
        }
        #endregion 
        #region 生产单管理
        /// <summary>
        /// 获取销售列表
        /// </summary>
        /// <returns></returns>
        public ResultObjModel get_Sale_list(string name)
        {
            return CoreStartDo.ResultAction(result =>
            {
                string where = " where role_id in @role_ids";
                if (!string.IsNullOrWhiteSpace(name))
                {
                    where += " and (u_name like @name or login_name like @name)";
                }
                var result_list = _tool.di_db.GetList<rk_user>("select * from rk_user" + where, new { role_ids = new string[] { "Sale", "Sales_Manager", "Finance_Manager" }, name }).ToList().Select(s => new { id = s.uid, value = s.u_name });
                result.code = 0;
                result.msg = "success";
                result.data = result_list;
                return result;
            });
        }
        /// <summary>
        ///  
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public ResultListModel<get_work_order_details_pagelist_showlis> get_manager_workorder_list(get_work_order_details_pagelist_params query)
        {
            return CoreStartDo.ResultAction<ResultListModel<get_work_order_details_pagelist_showlis>>(result =>
            {
                string core_sql = $"select d.u_name,{string.Join(',', _tool.search_workorder_Item)} from sale_work_order_details a left JOIN sale_work_order b on a.work_order_id = b.work_order_id left join slot_template c on a.slot_template_id = c.template_id left join rk_user d on b.add_uid = d.uid";
                string where = "where 1=1";
                dynamic query_dy = new System.Dynamic.ExpandoObject();
                if (!string.IsNullOrWhiteSpace(query.uid))
                {
                    where += " and b.add_uid=@sale_uid";
                    query_dy.sale_uid = query.uid;
                }
                if (!string.IsNullOrWhiteSpace(query.baseusername))
                {
                    where += " and  b.baseusername like @baseusername";
                    query_dy.baseusername = $"%{query.baseusername}%";
                }
                if (!string.IsNullOrWhiteSpace(query.mchname))
                {
                    where += " and  b.mch_name like @mchname";
                    query_dy.mchname = $"%{ query.mchname}%";
                }
                if (!string.IsNullOrWhiteSpace(query.work_order_details_id))
                {
                    where += " and  a.work_order_details_id like @work_order_details_id";
                    query_dy.work_order_details_id = $"%{query.work_order_details_id}%";
                }
                if (query.work_approval_state.HasValue)
                {
                    where += " and  b.work_approval_state=@work_approval_state";
                    query_dy.work_approval_state = query.work_approval_state;
                }
                if (query.work_state.HasValue)
                {
                    where += " and  b.work_state=@work_state";
                    query_dy.work_state = query.work_state;
                }
                if (!string.IsNullOrWhiteSpace(query.start_time))
                {
                    where += " and  b.work_end_time>=@start_time";
                    query_dy.start_time = query.start_time;
                }
                if (!string.IsNullOrWhiteSpace(query.end_time))
                {
                    where += " and  b.work_end_time<=@end_time";
                    query_dy.end_time = query.end_time;
                }
                ResultListModel<get_work_order_details_pagelist_showlis> result_pagelist = _tool.di_db.GetPageList<get_work_order_details_pagelist_showlis>(core_sql, where, "b.addtime", query_dy, query.IsPage, query.page, query.pagesize);
                return result_pagelist;
            });
        }

        /// <summary>
        /// 获取页面详情
        /// </summary>
        /// <param name="work_order_id"></param>
        /// <returns></returns>
        public ResultObjModel get_work_details_list(string work_order_id)
        {
            return CoreStartDo.ResultAction(result =>
            {
                //获取
                var box_list = _tool.di_db.GetList<get_details_model>("select a.*,b.*,c.u_name,d.slot_group from sale_work_order_details a left join sale_work_order b on a.work_order_id = b.work_order_id left join rk_user c on b.add_uid = c.uid left join slot_template d on a.slot_template_id = d.template_id where b.work_order_id=@work_order_id", new { work_order_id }).ToList();
                foreach(var item in box_list)    
                {
                    item.barcode = _barcode_service.GenerateBarCodeBitmap(item.work_order_details_id);
                }
                result.code = 0;
                result.msg = "success";
                result.data = box_list;
                return result;
            });
        } 
        /// <summary>
        /// 获取销售列表
        /// </summary>
        /// <returns></returns>
        public ResultObjModel get_Work_Manager_list(string name)
        {
            return CoreStartDo.ResultAction(result =>
            {
                string where = " where role_id in @role_ids";
                if (!string.IsNullOrWhiteSpace(name))
                {
                    where += " and (u_name like @name or login_name like @name)";
                }
                var result_list = _tool.di_db.GetList<rk_user>("select * from rk_user" + where, new { role_ids = new string[] { "Work_Manager", "Finance_Manager" }, name }).ToList().Select(s => new { id = s.uid, value = s.u_name });
                result.code = 0;
                result.msg = "success";
                result.data = result_list;
                return result;
            });
        }
        /// <summary>
        /// 审核通过转生产
        /// </summary>
        /// <returns></returns>
        public ResultModel to_work(string work_order_id, string uid)
        {
            return CoreStartDo.ResultAction(result =>
            {
                if (string.IsNullOrWhiteSpace(work_order_id))
                {
                    result.code = 1;
                    result.msg = "缺少关键参数";
                    return result;
                }
                if (string.IsNullOrWhiteSpace(uid))
                {
                    result.code = 1;
                    result.msg = "请选择生产主管";
                    return result;
                }
                var usermod = _tool.di_db.GetList<rk_user>("select * from rk_user where uid=@uid", new { uid }).FirstOrDefault();
                if (usermod == null)
                {
                    result.code = 1;
                    result.msg = "生产主管不存在";
                    return result;
                }
                if (usermod.role_id != "Work_Manager" && usermod.role_id != "Finance_Manager")
                {
                    result.code = 1;
                    result.msg = "所选员工并非生产主管";
                    return result;
                }
                var work_order = _tool.di_db.GetList<sale_work_order>("select top 1 * from sale_work_order where work_order_id=@work_order_id", new { work_order_id }).FirstOrDefault();
                if (work_order == null)
                {
                    result.code = 1;
                    result.msg = "生产单不存在";
                    return result;
                }
                if (work_order.total_state != sale_work_state_enum.审批处理中)
                {
                    result.code = 1;
                    result.msg = $"当前生产单{work_order.total_state.ToString()} 不允许转生产";
                    return result;
                }
                //更新审核状态为已完成
                int ur = _tool.di_db.do_Execute("update sale_work_order set total_state=@total_state,work_approval_state=@work_approval_state,approval_end_time=@approval_end_time,work_state=@work_state,work_uid=@work_uid where work_order_id=@work_order_id", new
                {
                    total_state = sale_work_state_enum.审批完成, //审核完成
                    work_approval_state = work_order_approval.已转生产,//审核完成转生产
                    work_state = work_state.待接单, //审核通过待接单
                    work_order.work_order_id,
                    approval_end_time = DateTime.Now, //设置生成生产单时间,
                    work_uid = uid
                });
                if (ur > 0)
                {
                    result.code = 0;
                    result.msg = "审核成功";
                }
                else
                {
                    result.code = 1;
                    result.msg = "审核成功";
                }
                return result;
            });
        }
        /// <summary>
        /// 更改客户
        /// </summary>
        /// <returns></returns>
        public ResultModel change_baseuserid(string work_order_id,string new_baseuserid)
        {
            return CoreStartDo.ResultAction(result =>
            {
                if (string.IsNullOrWhiteSpace(work_order_id))
                {
                    result.code = 1;
                    result.msg = "缺少关键参数";
                    return result;
                }
                var work_order = _tool.di_db.GetList<sale_work_order>("select top 1 * from sale_work_order where work_order_id=@work_order_id", new { work_order_id }).FirstOrDefault();
                if (work_order == null)
                {
                    result.code = 1;
                    result.msg = "生产单不存在";
                    return result;
                }
                //if (work_order.total_state != sale_work_state_enum.审批处理中)
                //{
                //    result.code = 1;
                //    result.msg = $"当前生产单{work_order.total_state.ToString()}";
                //    return result;
                //}
                var baseusermod = _tool.di_db.Get_rk_List<User>("select top 1 * from [User] where id=@id", new { id = new_baseuserid }).FirstOrDefault();
                if (baseusermod == null)
                {
                    result.code = 1;
                    result.msg = $"转移用户不存在";
                    return result; 
                }
                //变更所有人
                int ur = _tool.di_db.do_Execute("update sale_work_order set baseuserid=@baseuserid,baseusername=@baseusername where work_order_id=@work_order_id", new
                {
                    baseuserid = baseusermod.Id,
                    baseusername = baseusermod.Name,
                    work_order.work_order_id,
                }); 
                if (ur > 0)
                {
                    //变更工单下机器所有人 
                    string rkerror = "";
                    int rkdb_rows = _tool.di_db.StartRKTran((conn, tran) =>
                    {
                        int rows = 0;
                        //机器
                        rows += conn.Execute("update Mch set work_baseuserid=@new_baseuserid  where work_order_id=@work_order_id", new { work_order_id, new_baseuserid }, tran);
                        //机器柜体情况
                        rows += conn.Execute("update Mch_subsidiary set work_baseuserid=@new_baseuserid  where work_order_id=@work_order_id", new { work_order_id, new_baseuserid }, tran);
                        return rows;
                    }, ref rkerror);
                    if (rkdb_rows > 0)
                    {
                        result.code = 0;
                        result.msg = "变更成功";
                    }
                    else {
                        result.code = 0;
                        result.msg = "变更失败 " + rkdb_rows;
                    }
                }
                else
                {
                    result.code = 1;
                    result.msg = "变更成功";
                }
                return result;
            });
        }
        /// <summary>
        /// 获取客户信息(老-新)
        /// </summary>
        /// <param name="old_baseuserid"></param>
        /// <param name="new_baseuserid"></param>
        /// <returns></returns>
        public ResultObjModel get_user_mod(string old_baseuserid, string new_baseuserid)
        {
            return CoreStartDo.ResultAction(result =>
            {
                var userinfo = _tool.di_db.Get_rk_List<User>("select top 2 * from [User] where id in @ids", new { ids = new string[] { old_baseuserid, new_baseuserid } }).Select(s => new { s.Id, s.Name, s.Tel, s.UserName }).ToList();
                result.code = 0;
                result.msg = "success";
                result.data = new
                {
                    old_mod = userinfo.Where(s => s.Id == old_baseuserid).FirstOrDefault(),
                    new_mod = userinfo.Where(s => s.Id == new_baseuserid).FirstOrDefault()
                };
                return result;
            });
        } 
        /// <summary>
        /// 设置工期
        /// </summary>
        /// <returns></returns>
        public ResultModel set_work_end_time(string work_order_id, string work_end_time)
        {
            return CoreStartDo.ResultAction(result =>
            {
                DateTime? settime = null;
                if (!string.IsNullOrWhiteSpace(work_end_time))
                {
                    DateTime dt = DateTime.Now;
                    if (!DateTime.TryParse(work_end_time, out dt))
                    {
                        result.code = 1;
                        result.msg = "时间格式化错误";
                        return result;
                    }
                    if (string.IsNullOrWhiteSpace(work_order_id))
                    {
                        result.code = 1;
                        result.msg = "缺少关键参数";
                        return result;
                    }
                    settime = dt;

                } 
                var work_order = _tool.di_db.GetList<sale_work_order>("select top 1 * from sale_work_order where work_order_id=@work_order_id", new { work_order_id }).FirstOrDefault();
                if (work_order == null)
                {
                    result.code = 1;
                    result.msg = "生产单不存在";
                    return result;
                }
                if (work_order.total_state != sale_work_state_enum.审批处理中)
                {
                    result.code = 1;
                    result.msg = $"当前生产单{work_order.total_state.ToString()} 不允许设置工期";
                    return result;
                }
                //设置工期
                int ur = _tool.di_db.do_Execute("update sale_work_order set work_end_time=@work_end_time where work_order_id=@work_order_id", new
                {
                    work_end_time = settime,
                    work_order.work_order_id,
                });
                if (ur > 0)
                {
                    result.code = 0;
                    result.msg = "设置成功";
                }
                else
                {
                    result.code = 1;
                    result.msg = "设置成功";
                }
                return result;
            });
        }  
        /// <summary>
        /// 退回销售
        /// </summary>
        /// <returns></returns>
        public ResultModel approval_back_work(string work_order_id)
        {
            return CoreStartDo.ResultAction(result =>
            {
                if (string.IsNullOrWhiteSpace(work_order_id))
                {
                    result.code = 1;
                    result.msg = "缺少关键参数";
                    return result;
                }  
                var work_order = _tool.di_db.GetList<sale_work_order>("select top 1 * from sale_work_order where work_order_id=@work_order_id", new { work_order_id }).FirstOrDefault();
                if (work_order == null)
                {
                    result.code = 1;
                    result.msg = "生产单不存在";
                    return result;
                }
                if (work_order.total_state != sale_work_state_enum.审批处理中
                && work_order.total_state != sale_work_state_enum.生产退回
                 && work_order.total_state != sale_work_state_enum.审批完成  //2020 06 19 修改审批完成也能退回销售
                )
                {
                    result.code = 1;
                    result.msg = $"当前生产单{work_order.total_state.ToString()} 不允许退回销售";
                    return result;
                }
                //更新审核状态为已完成
                int ur = _tool.di_db.do_Execute("update sale_work_order set total_state=@total_state,work_approval_state=@work_approval_state,approval_back_time=@approval_back_time,work_state=null where work_order_id=@work_order_id", new
                {
                    total_state = sale_work_state_enum.审批被驳回, //审核完成
                    work_approval_state = work_order_approval.退回,//审核完成转生产 
                    work_order.work_order_id,
                    approval_back_time = DateTime.Now//设置生成生产单时间, 
                });
                if (ur > 0)
                {
                    result.code = 0;
                    result.msg = "退回成功";
                }
                else
                {
                    result.code = 1;
                    result.msg = "退回成功";
                }
                return result;
            });
        }
        #endregion
    }
}
